<template>
  <div>
    <PlainCreateBtn :show-icon="false" @click="openDialog">设置筛选条件<span v-if="!isEmpty">（已设置）</span></PlainCreateBtn>
    <el-checkbox v-model="selectWidget.options.isFillPreset" :disabled="isEmpty">将筛选条件设为默认数据</el-checkbox>
    <el-dialog
      :visible.sync="dialogVisible"
      :append-to-body="true"
      class="normal-common-dialog-size"
      @close="closeDialog">
      <div class="flex-center">
        <Title title="筛选项配置" />
      </div>
      <div :style="maxHeight?{maxHeight: maxHeight}:''" class="main filter-content">
        <el-form :rules="{}" label-width="82px" label-position="right" class="setting-form" @submit.native.prevent>
          <div class="list-item">
            <!-- input -->
            <template v-if="inputFilterList && inputFilterList.length">
              <filterInput
                v-for="item in inputFilterList"
                :key="item.keyword"
                v-model="presetFilter"
                :item="item"
                class="filter-form-item"/>
            </template>
            <!-- rangeDate -->
            <template v-if="dateFilterList && dateFilterList.length">
              <filterDate
                v-for="item in dateFilterList"
                :key="item.keyword"
                v-model="presetFilter"
                :item="item"
                class="filter-form-item"
                @datePickerTime="datePickerTime"/>
            </template>
          </div>
          <!-- select -->
          <div v-if="selectFilterList && selectFilterList.length" class="list-item">
            <filterSelect v-for="item in selectFilterList" :key="item.keyword" v-model="presetFilter" :item="item" />
          </div>
        </el-form>
      </div>
      <div class="btn-container">
        <el-button type="primary" size="small" @click="toSubmit">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="closeDialog">取消</el-button>
        <div class="button-text" @click="resetParams">重置</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import FilterValue from '../../filterValue';
import deleteGroupIcon from '@/assets/legalProcess/deleteIcon.png';
import copyGroupIcon from '@/assets/legalProcess/copyIcon.png';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import { createConfig } from '@/components/Common/relatedProcess/data';
// import ElMessage from '@/utils/message';
import filterInput from '@/components/Tool/input';
import filterSelect from '@/components/Tool/select';
import filterDate from '@/components/Tool/date';
import { getCommonApprovalFilterList } from '@/api/approvalModule';
import filterFun from '@/views/approvalModule/mixins/filterFun';
import { getDepartmentAll } from '@/api/config';
import { linkFormPresetFilter } from '@/utils/secret';

export default {
  components: { Title, FilterValue, EmptyPlaceholder, filterInput, filterSelect, filterDate },
  mixins: [filterFun],
  model: {
    prop: 'selectWidget',
    event: 'changeData'
  },
  props: {
    selectWidget: {
      type: Object,
      default: () => ({})
    },
    widgetData: {
      type: Object,
      default: () => ({ list: [], config: {}})
    }
  },
  data() {
    return {
      deleteGroupIcon, copyGroupIcon,
      dialogVisible: false,
      presetFilter: {},
      maxHeight: '',
      filterList: [],
      deptTreeList: [],
      configData: null
    };
  },
  computed: {
    isEmpty() {
      return !this.selectWidget.options.presetFilter || JSON.stringify(this.selectWidget.options.presetFilter) === '{}';
    },
    moduleId() {
      if (!this.selectWidget.options || !this.selectWidget.options.remoteParams) {
        return null;
      }
      return this.selectWidget.options.remoteParams.workFlowId;
    },
    dateFilterList() {
      const typeArr = ['date', 'rangeDate', 'complexRangeDate'];
      return this.filterList.map(i => {
        if (typeArr.includes(i.type)) {
          return i;
        }
      }).filter(i => !!i);
    },
    inputFilterList() {
      const typeArr = ['input', 'inputRange', 'inputSearch'];
      return this.filterList.map(i => {
        if (typeArr.includes(i.type)) { return i; }
      }).filter(i => !!i);
    },
    selectFilterList() {
      const typeArr = ['select', 'cascaderSelectWithChild', 'cascaderSelect', 'mulSelect', 'loadMoreSelect', 'regionSelect', 'addressSelect'];
      return this.filterList.map(i => {
        if (typeArr.includes(i.type)) { return i; }
      }).filter(i => !!i);
    },
    isContractForm() { // 是否合同类型的固定表单
      const options = this.selectWidget.options.remoteParams;
      if (options.isCustom || options.type !== 0) {
        return false;
      }
      return true;
    }
  },
  created() {
    if (this.selectWidget.options.isFillPreset === undefined) {
      this.$set(this.selectWidget.options, 'isFillPreset', false);
    }
  },
  methods: {
    openDialog() {
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 2) / 3) - 100 + 'px';
      const presetFilter = _.cloneDeep(this.selectWidget.options.presetFilter || {});
      if (!this.selectWidget.options.remoteParams.isCustom) {
        const type = this.selectWidget.options.remoteParams.type;
        createConfig(type).then(res => {
          this.configData = res;
          this.filterList = res.filterList;

          this.presetFilter = presetFilter;
          this.dialogVisible = true;
        });
      } else {
        const workFlowId = this.selectWidget.options.remoteParams.workFlowId;
        getCommonApprovalFilterList(workFlowId).then(async(filterData) => {
          const typeList = filterData.data.map(i => i.type);
          if (typeList.includes('department')) {
            const deptResult = await getDepartmentAll() || {};
            this.deptTreeList = deptResult.data || [];
          }
          this.filterList = this.setFilterList(filterData.data || []);
          this.presetFilter = presetFilter;
          this.dialogVisible = true;
        });
      }
    },
    closeDialog() {
      this.dialogVisible = false;
      this.presetFilter = {};
    },
    toSubmit() {
      const presetFilter = _.cloneDeep(this.presetFilter || {});
      for (const key of Object.keys(presetFilter)) {
        const normalEmpty = _.isNil(presetFilter[key]) || presetFilter[key] === '';
        const arrayEmpty = Array.isArray(presetFilter[key]) && presetFilter[key].length === 0;
        if (normalEmpty || arrayEmpty) {
          delete presetFilter[key];
        }
      }

      if (this.selectWidget.options.remoteParams.isCustom) {
        const params = this.setDynamicFilter(presetFilter);
        if (params && JSON.stringify(params) !== '{}') {
          params.fromProcess = 1;
        }
        this.$set(this.selectWidget.options, 'presetFilterParams', linkFormPresetFilter(params));
      } else {
        const params = _.cloneDeep(presetFilter);
        if (params && JSON.stringify(params) !== '{}') {
          params.fromProcess = 1;
          if (this.isContractForm) {
            params.handleStatus = -1;
            params.excludeProcess = 0; // 固定参数,过滤草稿状态的合同
            params.hasContractCode = true; // 只筛选已经生成合同编码的合同
          }
        }
        if (this.configData && this.configData.handelParams) {
          this.configData.handelParams(params);
        }
        this.$set(this.selectWidget.options, 'presetFilterParams', linkFormPresetFilter(params));
      }
      this.$set(this.selectWidget.options, 'presetFilter', presetFilter);
      this.closeDialog();

      if (this.isEmpty) this.$set(this.selectWidget.options, 'isFillPreset', false);
    },
    // filter
    datePickerTime({ val, key }) {
      if (!val) {
        delete this.presetFilter[key];
      }
    },
    resetParams() {
      this.presetFilter = {};
    }
  }
};
</script>

<style lang="scss" scoped>
.flex-center {
  display: flex;
  align-items: center;
}
.main {
  margin: 20px 0;
  @include scrollBar($width: 6px);
}
.filter-item {
  @extend .flex-center;
  margin-bottom: 20px;
  .delete-icon, .copy-icon {
    width: 12px;
    cursor: pointer;
    margin-left: 9px;
  }
}
.btn-container {
  @extend .flex-center;
  justify-content: center;
  .button-text {
    margin-left: 10px;
  }
}

.filter-content {
  position: relative;
  &::v-deep {
    .el-form-item__label, .el-form-item__content {
      line-height: 32px !important;
    }
    .el-form {
      display: flex;
      flex-direction: column;
      .el-form-item {
        margin-bottom: 20px;
        &.select-form-item {
          .el-input {
            width: 100px;
          }
        }
        &.input-form-item {
          .el-input {
            width: 240px;
          }
        }
      }
      .filter-form-item:nth-child(odd) {
        margin-right: 32px;
      }
      .filter-form-item {
        .el-input, .el-textarea {
          width: 240px;
        }
      }
      .el-input__inner::-webkit-input-placeholder {
        color: #ddd;
      }
      .el-range-input::-webkit-input-placeholder {
        color: #ddd;
      }
    }
  }
  .list-item {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    &:first-child {
      border-top: none;
      padding-top: 0;
    }
  }
}
</style>
